﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using ERP_RORZE_SYSTEM;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ERP_RORZE_DLL.Assembly
{
    public partial class frm_Add_MaterialOrderDetail : Form
    {
        public string order_number;

        private INISettings mySetting;
        private SqlConnection myConnection;

        public frm_Add_MaterialOrderDetail()
        {
            InitializeComponent();

            this.mySetting = new INISettings();
            this.myConnection = new SqlConnection(mySetting.SQLConnectionString);

            this.order_number = null;

            LoadMaterial();

            this.materialID.SelectedIndexChanged += materialID_SelectedIndexChanged;
            this.quantityValue.LostFocus += quantityValue_LostFocus;
            
        }

        void quantityValue_LostFocus(object sender, EventArgs e)
        {
            updateInfo();
        }

        private void updateInfo()
        {
            if (!string.IsNullOrEmpty(this.quantityValue.Text))
            {
                float qty = 0;
                if (float.TryParse(this.quantityValue.Text, out qty))
                {
                    if (qty <= 0)
                    {
                        MessageBox.Show("Quantity must be greater than 0.");
                    }
                    else
                    {
                        if (this.materialID.SelectedIndex > 0)
                        {
                            ComboboxItem item = (ComboboxItem)this.materialID.SelectedItem;
                            string err = checkQuantity(item.Value.ToString(), qty);
                            if (string.IsNullOrEmpty(err))
                            {
                                string[] quotation = calculatePrice(item.Value.ToString(), qty);
                                this.priceValue.Text = quotation[0];
                                this.currencyID.Text = quotation[1];
                            }
                            else
                            {
                                MessageBox.Show(err);
                            }
                        }       
                    }
                }
                else
                {
                    MessageBox.Show("Invalid quantity");
                }
            }
        }

        ///////////////////////////////////
        /// Check MOQ and Marume
        //////////////////////////////////
        private string checkQuantity(string part, float qty)
        {
            string ret = null;
            float moq = 0;
            float marume = 0;
            try
            {
                myConnection.Open();
                SqlCommand sql_cmd = myConnection.CreateCommand();
                sql_cmd.CommandText = "SELECT [Marume], [MinQuantity]"
                    + " FROM [222_Part] WHERE PartNo='" + part + "'";
                SqlDataReader dataReader = sql_cmd.ExecuteReader();
                if (dataReader.Read())
                {
                    if (dataReader["MinQuantity"] != DBNull.Value)
                    {
                        if (float.TryParse(dataReader["MinQuantity"].ToString(), out moq))
                        {
                            if (moq == 0) moq = 1;
                        }
                        else
                        {
                            moq = 1;
                        }
                    }
                    else
                    {
                        moq = 1;
                    }

                    if (dataReader["Marume"] != DBNull.Value)
                    {
                        if (float.TryParse(dataReader["Marume"].ToString(), out marume))
                        {
                            if (marume == 0) marume = 1;
                        }
                        else
                        {
                            marume = 1;
                        }
                    }
                    else
                    {
                        marume = 1;
                    }
                }
                dataReader.Close();
                sql_cmd.Dispose();
                myConnection.Close();

                if (qty < moq)
                {
                    ret = "Quantity must be greater than MOQ: " + moq.ToString() + "\r\n";
                }
                else
                {
                    if ((qty % marume) > 0)
                    {
                        ret = "Quantity must be divisible by Marume: " + marume.ToString();
                    }
                }
            }
            catch
            {
                if (myConnection.State == ConnectionState.Open)
                {
                    myConnection.Close();
                }
                ret = "Cannot check MOQ and Marume.";
            }
            return ret;
        }

        //////////////////////////////////////////////
        /// Calcaulate Price with PartNo and Quantity
        //////////////////////////////////////////////
        private string[] calculatePrice(string part, float qty)
        {
            string[] ret = new string[2];
            ret[0] = "0";
            ret[1] = "USD";

            float max_qty = 0;
            bool pass = true;
            try
            {
                myConnection.Open();
                SqlCommand cmd_sql = myConnection.CreateCommand();
                cmd_sql.CommandText = "SELECT Quantity"
                    + " FROM [241_ImportQuotation] WHERE PartNo='" + part + "' AND Quantity < 99999"
                    + " ORDER BY Quantity DESC";
                SqlDataReader dataReader = cmd_sql.ExecuteReader();
                if (dataReader.Read())
                {
                    max_qty = float.Parse(dataReader["Quantity"].ToString());
                }
                dataReader.Close();
                cmd_sql.Dispose();
                myConnection.Close();
            }
            catch (Exception ex)
            {
                if (myConnection.State == ConnectionState.Open)
                {
                    myConnection.Close();
                }
                MessageBox.Show(ex.Message);
                pass = false;
            }

            if (pass)
            {
                if (qty < max_qty)
                {
                    try
                    {
                        myConnection.Open();
                        SqlCommand cmd_sql = myConnection.CreateCommand();
                        cmd_sql.CommandText = "SELECT Price, CurrencyID"
                            + " FROM [241_ImportQuotation] WHERE PartNo='" + part + "'"
                            + " AND Quantity<=" + qty
                            + " ORDER BY Price";
                        SqlDataReader dataReader = cmd_sql.ExecuteReader();
                        if (dataReader.Read())
                        {
                            ret[1] = dataReader["CurrencyID"].ToString();
                            ret[0] = dataReader["Price"].ToString();
                        }
                        dataReader.Close();
                        cmd_sql.Dispose();
                        myConnection.Close();
                    }
                    catch
                    {
                        if (myConnection.State == ConnectionState.Open)
                        {
                            myConnection.Close();
                        }
                        MessageBox.Show("Cannot get price for this PartNo.");
                    }
                }
                else
                {
                    try
                    {
                        myConnection.Open();
                        SqlCommand cmd_sql = myConnection.CreateCommand();
                        cmd_sql.CommandText = "SELECT Price, CurrencyID"
                            + " FROM [241_ImportQuotation] WHERE PartNo='" + part + "'"
                            + " ORDER BY Price";
                        SqlDataReader dataReader = cmd_sql.ExecuteReader();
                        if (dataReader.Read())
                        {
                            ret[1] = dataReader["CurrencyID"].ToString();
                            ret[0] = dataReader["Price"].ToString();
                        }
                        dataReader.Close();
                        cmd_sql.Dispose();
                        myConnection.Close();
                    }
                    catch
                    {
                        if (myConnection.State == ConnectionState.Open)
                        {
                            myConnection.Close();
                        }
                        MessageBox.Show("Cannot get price for this PartNo.");
                    }
                }
            }
            else
            {
                MessageBox.Show("Cannot get price for this PartNo.");
            }

            return ret;
        }

        ////////////////////////////////////////////
        /// When change Material
        ///////////////////////////////////////////
        void materialID_SelectedIndexChanged(object sender, EventArgs e)
        {
            ComboboxItem item = (ComboboxItem)this.materialID.SelectedItem;
            try
            {
                myConnection.Open();
                SqlCommand cmd_sql = myConnection.CreateCommand();
                cmd_sql.CommandText = "SELECT t1.ROHS, t1.MinQuantity, t1.Marume, t1.Remark, t1.PackingNote, t2.EnglishName"
                    + " FROM [222_Part] AS t1 LEFT JOIN [222_Maker] AS t2 ON t1.MakerID=t2.MakerID"
                    + " WHERE t1.PartNo='" + item.Value.ToString() + "'";
                SqlDataReader dataReader = cmd_sql.ExecuteReader();
                if (dataReader.Read())
                {
                    this.moqValue.Text = dataReader["MinQuantity"].ToString();
                    this.marumeValue.Text = dataReader["Marume"].ToString();
                    if (dataReader["ROHS"] != DBNull.Value)
                    {
                        if ((bool)dataReader["ROHS"])
                        {
                            this.roHS.Text = "";
                        }
                        else
                        {
                            this.roHS.Text = "RoHS-OK";
                        }                        
                    }
                    else
                    {
                        this.roHS.Text = "RoHS-OK";
                    }
                                        
                    if (string.IsNullOrEmpty(dataReader["Remark"].ToString()))
                    {
                        this.quantityUnit.Text = dataReader["PackingNote"].ToString();
                    }
                    else
                    {
                        this.quantityUnit.Text = dataReader["Remark"].ToString();
                    }
                    
                    this.makerID.Text = dataReader["EnglishName"].ToString();
                    
                }
                dataReader.Close();
                cmd_sql.Dispose();
                myConnection.Close();
            }
            catch (Exception ex)
            {
                if (myConnection.State == ConnectionState.Open)
                {
                    myConnection.Close();
                }
                MessageBox.Show(ex.Message);
                //MessageBox.Show("Cannot get Material List");
            }

            updateInfo();
        }
        
        //////////////////////////////////////////////
        /// Load Material List
        //////////////////////////////////////////////
        private void LoadMaterial()
        {
            try
            {
                myConnection.Open();
                SqlCommand cmd_sql = myConnection.CreateCommand();
                cmd_sql.CommandText = "SELECT PartNo FROM [222_Part]"
                    + " WHERE PType = 'P'"
                    + " ORDER BY PartNo";
                SqlDataReader dataReader = cmd_sql.ExecuteReader();
                while (dataReader.Read())
                {
                    ComboboxItem item = new ComboboxItem();
                    item.Text = dataReader["PartNo"].ToString().Trim();
                    item.Value = dataReader["PartNo"].ToString().Trim();

                    this.materialID.Properties.Items.Add(item);
                }                
                dataReader.Close();
                cmd_sql.Dispose();
                myConnection.Close();
            }
            catch
            {
                if (myConnection.State == ConnectionState.Open)
                {
                    myConnection.Close();
                }

                MessageBox.Show("Cannot get Material information");
            }
        }

        /////////////////////////////////////
        /// Set Order No
        ////////////////////////////////////
        public void setOrderNo(string value)
        {
            order_number = value;
            this.orderNo.Text = value;
        }

        private void buttonCancel_Click(object sender, EventArgs e)
        {
            this.Dispose();
        }

        private void buttonAdd_Click(object sender, EventArgs e)
        {
            string error = null;
            DateTime dead_line = new DateTime();
            int quantity = 0;
            string qty = null;
            ComboboxItem item = new ComboboxItem();

            if (this.materialID.SelectedIndex < 0)
            {
                error = "Please select material";
            }
            else
            {
                item = (ComboboxItem)this.materialID.SelectedItem;
            }

            if (string.IsNullOrEmpty(error))
            {
                if (this.deadLine.EditValue != null)
                {
                    dead_line = DateTime.Parse(this.deadLine.EditValue.ToString());
                }

                if (!string.IsNullOrEmpty(this.quantityValue.Text))
                {
                    if (Int32.TryParse(this.quantityValue.Text, out quantity))
                    {
                        qty = quantity.ToString();
                    }
                }

                try
                {
                    myConnection.Open();
                    string sql = "INSERT INTO [444_MaterialOrderDetail] (OrderNo, MaterialID, Quantity, DeadLine)"
                        + " VALUES ('" + order_number + "', '" + item.Value.ToString() + "', " + qty + ", @deadline)";
                    SqlCommand cmd_sql = new SqlCommand(sql, myConnection);
                    cmd_sql.Parameters.Add("@deadline", SqlDbType.DateTime).Value = dead_line.Date;
                    cmd_sql.ExecuteNonQuery();
                    cmd_sql.Dispose();
                    myConnection.Close();
                    MessageBox.Show("Material Orther Detail added success.");
                }
                catch //(Exception ex)
                {
                    if (myConnection.State == ConnectionState.Open)
                    {
                        myConnection.Close();
                    }
                    //MessageBox.Show(ex.Message);
                    MessageBox.Show("Cannot add Material Order Detail. Please try again.");
                }
            }

            if (!string.IsNullOrEmpty(error))
            {
                MessageBox.Show(error);
            }
        }
    }
}
